package com.main.ok.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketException;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.nio.charset.Charset;

/**
 * Created by kai on 2015/6/11 0011.
 * udp实现的接受和发送逻辑
 */
public class DataGramChannelTest {
    public static void main(String[] args) throws IOException, InterruptedException {
        new Thread(new DataChannelListening()).start();
        //sleep
        Thread.sleep(1000L);
        //start send
        new Thread(new DataChannelSend()).start();
    }

    private static class DataChannelSend extends Thread {

        @Override
        public void run() {
            try {
                String data = "i love nio " + System.currentTimeMillis();
                ByteBuffer buffer = ByteBuffer.allocate(48);
                buffer.clear();
                buffer.put(data.getBytes());
                buffer.flip();
                DatagramChannel channel = DatagramChannel.open();
//                channel.connect(new InetSocketAddress(2222));
                channel.send(buffer, new InetSocketAddress("localhost", 2222));
                channel.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private static class DataChannelListening extends Thread {
        @Override
        public void run() {
            //
            try {
                DatagramChannel datagramChannel = DatagramChannel.open();
                datagramChannel.configureBlocking(false);
                datagramChannel.socket().bind(new InetSocketAddress(2222));
                ByteBuffer buffer = ByteBuffer.allocate(48);
                buffer.clear();
                System.out.println("start listening Port:2222");
                while (datagramChannel.receive(buffer) == null) {
                    Thread.sleep(300L);
                }
                buffer.flip();
                String recvInfo = Charset.forName("utf-8").newDecoder().decode(buffer).toString();
                System.out.println(recvInfo);
            } catch (IOException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
